{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:05:33.314605Z",
     "start_time": "2018-09-06T07:05:30.266337Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import matplotlib as mpl \n",
    "%matplotlib inline\n",
    "from pandas.tseries.offsets import DateOffset\n",
    "import pickle\n",
    "import tensorflow as tf\n",
    "import random as rn\n",
    "import os\n",
    "os.environ['PYTHONHASHSEED'] = '0'\n",
    "np.random.seed(42)\n",
    "rn.seed(12345)\n",
    "tf.set_random_seed(1234)\n",
    "\n",
    "# 设置中文编码和负号的正常显示\n",
    "plt.rcParams['font.sans-serif'] = 'simhei'\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "Path = 'D:\\\\APViaML'\n",
    "pd.set_option('display.max_columns', 50)\n",
    "pd.set_option('display.max_rows', 100)\n",
    "pd.set_option('display.float_format', lambda x: '%.3f' % x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:05:39.125043Z",
     "start_time": "2018-09-06T07:05:38.441234Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_demo_dict_data():\n",
    "    file = open(Path + '\\\\data\\\\alldata_demo_top1000.pkl','rb')\n",
    "    raw_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return raw_data\n",
    "\n",
    "data = get_demo_dict_data()\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:05:45.120250Z",
     "start_time": "2018-09-06T07:05:45.081147Z"
    }
   },
   "outputs": [],
   "source": [
    "X_factor_macrolist = pd.read_excel(Path + '\\\\data\\\\List.xlsx',sheet_name='Macro')\n",
    "X_factor_macrolist = X_factor_macrolist['Acronym']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:05:50.999209Z",
     "start_time": "2018-09-06T07:05:50.993694Z"
    }
   },
   "outputs": [],
   "source": [
    "def creat_test_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "    return X_testdata, Y_testdata\n",
    "\n",
    "def Evaluation_fun(predict_array,real_array):\n",
    "    List1 = []\n",
    "    List2 = []\n",
    "    if len(predict_array) != len(real_array):\n",
    "        print('Something is worng!')\n",
    "    else:\n",
    "        for i in range(len(predict_array)):\n",
    "            List1.append(np.square(predict_array[i]-real_array[i]))\n",
    "            List2.append(np.square(real_array[i]))\n",
    "        result = round(100*(1 - sum(List1)/sum(List2)),3)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:06:08.764848Z",
     "start_time": "2018-09-06T07:06:08.759837Z"
    }
   },
   "outputs": [],
   "source": [
    "y_real = np.array(top_1000_data_Y.loc['1988':])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:59:55.016109Z",
     "start_time": "2018-09-06T07:47:01.163339Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ENet\n",
      "RF\n",
      "GBRT\n"
     ]
    }
   ],
   "source": [
    "model_list1 = ['ENet','RF','GBRT']\n",
    "for x in model_list1:\n",
    "    model_name = str(x)\n",
    "    print(model_name)\n",
    "    score_loss_list = []\n",
    "    for j in range(8+1):   \n",
    "        if j == 0:\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'Model_'+model_name+'_Top1000_Prediction.pkl'\n",
    "                file = open(model_filepath,'rb')\n",
    "                best_model = pickle.load(file)\n",
    "                file.close()        \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list \n",
    "            R_real = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "            \n",
    "        else:\n",
    "            j = j-1\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                num_list = np.array(range(1,753,8)) + j + 93\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                X_testdata[:,num_list] = 0\n",
    "\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'Model_'+model_name+'_Top1000_Prediction.pkl'\n",
    "                file = open(model_filepath,'rb')\n",
    "                best_model = pickle.load(file)\n",
    "                file.close()        \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list\n",
    "\n",
    "        new_score = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "        score_loss = new_score - R_real\n",
    "        score_loss_list.append(score_loss)\n",
    "\n",
    "    file = open(Path + '\\\\output\\\\data\\\\'+ model_name +'macro_char_importance.pkl', 'wb')\n",
    "    pickle.dump(score_loss_list, file)\n",
    "    file.close()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T08:42:22.833711Z",
     "start_time": "2018-09-06T08:03:18.163603Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NN1\n",
      "NN2\n",
      "NN3\n"
     ]
    }
   ],
   "source": [
    "from keras.models import load_model\n",
    "from keras import backend as K\n",
    "K.clear_session()\n",
    "tf.reset_default_graph()\n",
    "import gc\n",
    "model_list2 = ['NN1','NN2','NN3']\n",
    "for x in model_list2:\n",
    "    model_name = str(x)\n",
    "    print(model_name)\n",
    "    score_loss_list = []\n",
    "    for j in range(8+1):   \n",
    "        if j == 0:\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'_Model_'+model_name+'_Top1000_Prediction.h5'\n",
    "                best_model = load_model(model_filepath)   \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list[:,0]:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list \n",
    "                \n",
    "                K.clear_session()\n",
    "                tf.reset_default_graph()\n",
    "                gc.collect()\n",
    "                \n",
    "            R_real = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "            \n",
    "        else:\n",
    "            j = j-1\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                \n",
    "                num_list = np.array(range(1,753,8)) + j + 93\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                X_testdata[:,num_list] = 0\n",
    "\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'_Model_'+model_name+'_Top1000_Prediction.h5'\n",
    "                best_model = load_model(model_filepath)\n",
    "                \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list[:,0]:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list\n",
    "\n",
    "                K.clear_session()\n",
    "                tf.reset_default_graph()\n",
    "                gc.collect()\n",
    "                \n",
    "        new_score = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "        score_loss = new_score - R_real\n",
    "        score_loss_list.append(score_loss)\n",
    "\n",
    "    file = open(Path + '\\\\output\\\\data\\\\'+ model_name+'macro_char_importance.pkl', 'wb')\n",
    "    pickle.dump(score_loss_list, file)\n",
    "    file.close() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T07:59:55.561556Z",
     "start_time": "2018-09-06T07:59:55.557545Z"
    }
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
